package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.entity.User;
import com.example.springboot.entity.dto.req.WarningSignalReqDTO;
import com.example.springboot.entity.dto.resp.DocumentFileReturnRespDTO;
import com.example.springboot.entity.dto.resp.FileListDTO;
import com.example.springboot.entity.dto.resp.WarningSignalRespDTO;
import com.example.springboot.service.DocumentService;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * ClassName: DocumentServiceImpl
 * Package: com.example.springboot.service.impl
 * Description:
 *
 * @Author dhn
 * @Create 2024/4/7 21:29
 * @Version 1.0
 */
@Service
public class DocumentServiceImpl implements DocumentService {

    @Value("${storage-files.head.path}")
    private String folder;

    @Value("${storage-files.head.real-path}")
    private String realHeadPath;

    @Override
    public WarningSignalRespDTO getWarningSignal(WarningSignalReqDTO requestParam) {
        //拼接访问路径
        if(requestParam==null){
            return null;
        }
        String baseDirectory = null;
        String realPath = null;
        if(StrUtil.equals(requestParam.getRole(),"ROLE_ADMIN")){
            String roleClassName = StrUtil.equals(requestParam.getRoleClass(),"0")?"huazhong":"hubei";
            baseDirectory = folder+"/"+roleClassName+"/"+requestParam.getClassName()+"/"+requestParam.getFileName();
            realPath = realHeadPath + "/"+roleClassName+"/"+requestParam.getClassName()+"/"+requestParam.getFileName();
        }
        else if(StrUtil.equals(requestParam.getRole(),"ROLE_FARM_USER")||StrUtil.equals(requestParam.getRole(),"ROLE_JK_USER")){
            String roleClassName = "hubei";
            baseDirectory = folder+"/"+roleClassName+"/"+requestParam.getClassName()+"/"+requestParam.getFileName();
            realPath = realHeadPath + "/"+roleClassName+"/"+requestParam.getClassName()+"/"+requestParam.getFileName();
        }
        else if(StrUtil.equals(requestParam.getRole(),"ROLE_DW_USER")){
            String roleClassName = StrUtil.equals(requestParam.getRoleClass(),"0")?"huazhong":"hubei";
            baseDirectory = folder+"/"+roleClassName+"/"+requestParam.getClassName()+"/"+requestParam.getFileName();
            realPath = realHeadPath + "/"+roleClassName+"/"+requestParam.getClassName()+"/"+requestParam.getFileName();
        }

        File directory = new File(baseDirectory);
        List<String> fileNameList = new ArrayList<>();
        List<String> filePathList = new ArrayList<>();
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".pdf")) {
                        fileNameList.add(file.getName());
                        filePathList.add(realPath+"/"+file.getName());
                    }
                }
            }
        }
        // 创建一个索引流并将索引与列表内容结合，然后排序
        List<Integer> indices = IntStream.range(0, fileNameList.size())
                .boxed()
                .sorted((i, j) -> filePathList.get(j).compareTo(filePathList.get(i))) // 降序比较文件路径
                .collect(Collectors.toList());

        // 根据排序后的索引重构原列表
        List<String> sortedFileNames = indices.stream()
                .map(fileNameList::get)
                .collect(Collectors.toList());
        List<String> sortedFilePaths = indices.stream()
                .map(filePathList::get)
                .collect(Collectors.toList());

        // 更新列表
        fileNameList.clear();
        fileNameList.addAll(sortedFileNames);
        filePathList.clear();
        filePathList.addAll(sortedFilePaths);

        return WarningSignalRespDTO.builder()
                .fileNameList(fileNameList)
                .filePathList(filePathList)
                .build();
    }

    @Override
    public List<DocumentFileReturnRespDTO> getFileReturnService(User user, String className, String fileName) {
        // 确定角色对应的类别名称
        String roleClassName = getRoleClassName(user);
        String baseDirectory = folder + "/" + roleClassName + "/" + className + "/" + fileName;
        String realPath = realHeadPath + "/" + roleClassName + "/" + className + "/" + fileName;
        System.out.println(baseDirectory);
        System.out.println(realPath);
        // 获取排序后的文件名和文件路径
        Pair<List<String>, List<String>> sortedFiles = getFileListSortedByPath(baseDirectory, realPath);
        List<String> sortedFileNames = sortedFiles.getLeft();
        List<String> sortedFilePaths = sortedFiles.getRight();

        // 构建响应列表
        List<DocumentFileReturnRespDTO> responseList = new ArrayList<>();
        DocumentFileReturnRespDTO dto = createDocumentFileReturnDTO(sortedFileNames, sortedFilePaths, getNetworkName(user));
        if (dto.getFileList().size() > 12) {
            dto.setFileList(dto.getFileList().subList(0, 12));
        }
        responseList.add(dto);

        // 如果是管理员，还需要处理湖北电网的文件
        if (StrUtil.equals(user.getRole(), "ROLE_ADMIN")) {
            responseList.addAll(handleAdminSpecialCase(className, fileName));
        }

        return responseList;
    }


    private String getRoleClassName(User user) {
        switch (user.getRole()) {
            case "ROLE_ADMIN":
                return "huazhong";
            case "ROLE_FARM_USER":
            case "ROLE_JK_USER":
                return "hubei";
            case "ROLE_DW_USER":
                return StrUtil.equals(user.getRoleClass(), "0") ? "huazhong" : "hubei";
            default:
                return "unknown"; // 或者抛出异常
        }
    }

    private String getNetworkName(User user) {
        return StrUtil.equals(user.getRole(), "ROLE_ADMIN") || StrUtil.equals(user.getRoleClass(), "0") ? "华中电网" : "湖北电网";
    }

    private List<DocumentFileReturnRespDTO> handleAdminSpecialCase(String className, String fileName) {
        String roleClassName = "hubei";
        String baseDirectory = folder + "/" + roleClassName + "/" + className + "/" + fileName;
        String realPath = realHeadPath + "/" + roleClassName + "/" + className + "/" + fileName;
        System.out.println(baseDirectory);
        Pair<List<String>, List<String>> sortedFiles = getFileListSortedByPath(baseDirectory, realPath);
        List<String> sortedFileNames = sortedFiles.getLeft();
        List<String> sortedFilePaths = sortedFiles.getRight();

        List<DocumentFileReturnRespDTO> adminResponseList = new ArrayList<>();
        DocumentFileReturnRespDTO dto = createDocumentFileReturnDTO(sortedFileNames, sortedFilePaths, "湖北电网");
        if (dto.getFileList().size() > 12) {
            dto.setFileList(dto.getFileList().subList(0, 12));
        }
        adminResponseList.add(dto);
        return adminResponseList;
    }


    private DocumentFileReturnRespDTO createDocumentFileReturnDTO(List<String> fileNames, List<String> filePaths, String networkName) {
        List<FileListDTO> fileListDTOs = IntStream.range(0, fileNames.size())
                .mapToObj(i -> FileListDTO.builder()
                        .fileName(fileNames.get(i))
                        .fileUrl(filePaths.get(i))
                        .build())
                .collect(Collectors.toList());

        DocumentFileReturnRespDTO dto = new DocumentFileReturnRespDTO();
        dto.setFileList(fileListDTOs);
        dto.setName(networkName);
        return dto;
    }

    private Pair<List<String>, List<String>> getFileListSortedByPath(String baseDirectory, String realPath) {
        File directory = new File(baseDirectory);
        List<String> fileNameList = new ArrayList<>();
        List<String> filePathList = new ArrayList<>();

        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".pdf")) {
                        fileNameList.add(file.getName());
                        filePathList.add(realPath + "/" + file.getName());
                    }
                }
            }
        }

        List<Integer> indices = IntStream.range(0, fileNameList.size())
                .boxed()
                .sorted(Comparator.comparing(filePathList::get).reversed())
                .collect(Collectors.toList());

        List<String> sortedFileNames = indices.stream()
                .map(fileNameList::get)
                .collect(Collectors.toList());
        List<String> sortedFilePaths = indices.stream()
                .map(filePathList::get)
                .collect(Collectors.toList());

        return Pair.of(sortedFileNames, sortedFilePaths);
    }


}
